package com.lee.rpc.server.rpc;

import com.lee.rpc.model.Clothes;
import org.springframework.stereotype.Component;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * RpcServer
 *
 * @description
 * @author lihuanmin
 * @date 2021/12/8 11:24
 * @version v1.0
 */
@Component
public class RpcServer {

    public void run (int port) throws Exception{
        ServerSocket server = new ServerSocket();
        server.bind(new InetSocketAddress(port));
        ObjectInputStream input = null;
        ObjectOutputStream output = null;
        Socket socket = null;
        try {
            while (true) {
                socket = server.accept();
                input = new ObjectInputStream(socket.getInputStream());
                String serviceName = input.readUTF();
                String methodName = input.readUTF();
                Class<?>[] parameterTypes = (Class<?>[])input.readObject();
                Object[] arguments = (Object[])input.readObject();
                Class<?> serviceClass = ServiceConfig.SERVICE_REGISTRY.get(serviceName);
                Method method = serviceClass.getMethod(methodName, parameterTypes);
                Clothes clothes = (Clothes)method.invoke(serviceClass.newInstance(), arguments);
                output = new ObjectOutputStream(socket.getOutputStream());
                output.writeObject(clothes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert output != null;
            output.close();
            input.close();
            socket.close();
        }
    }
}
